
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>

int main(int argc, char* argv[]) {
  if(argc <= 1) {
    printf("please use:\n%s /dev/fd0 or other device\n", argv[0]);
    return -1;
  }
  char boot_buffer[512];
  int floppy_desc, file_desc;
  const char bin_file[] = "./boot.bin";
  const char* floppy = argv[1]; //"/dev/fd0";
  ssize_t retval = 0;
  file_desc = open(bin_file, O_RDONLY);
  if( file_desc <= 0 ) {
    printf("open %s failed\n", bin_file);
    return -1;
  } else {
    printf("open %s ok\n", bin_file);
  }
  
  retval = read(file_desc, boot_buffer, 510);
  if(-1 == retval) {
    printf("read file data error(%d)\n", errno);
  } else if(retval != 510) {
    printf("read file data error 510(%d)\n", retval);
    return -2;
  } else {
    printf("read file data ok\n");
    close(file_desc);
  }
   
  boot_buffer[510]=0x55;
  boot_buffer[511]=0xaa;
  
  floppy_desc=open(floppy, O_RDWR);
  if( floppy_desc <= 0 ) {
    printf("open %s failed, fd(%d) %d\n", floppy, floppy_desc, errno );
    return -3;
  } else {
    printf("open %s ok\n", floppy);
  }
  
  retval = lseek(floppy_desc, 0, SEEK_CUR);
  if(-1 == retval) {
    printf("lseek file %s failed, %d\n", floppy, errno );
    return -4;
  }
  
  retval = write(floppy_desc, boot_buffer, 512);
  if(-1 == retval) {
    printf("write to floppy failed, error(%d)\n", errno);
    return -5; 
  }
  
  retval = close(floppy_desc);
  if(0 == retval) {
    printf("close file ok\n");
  } else if( -1 == retval) {
    printf("close file error(%d)\n", errno);
  } else {
    assert(0); // not reachable
  }

  return 0;
}



